#include "cm_gpio_tool.h" // GPIO 工具头文件，包含 GPIO 初始化、写、读、翻转等函数

// 初始化 GPIO
int cm_gpio_init_tool(CM_GPIO_Handle_t *hgpio)
{
    if(hgpio == NULL)
        return -1;

    // 设置引脚复用
    if(cm_iomux_set_pin_func(hgpio->pin, hgpio->func) != 0)
    {
        cm_log_printf(0, "GPIO_%d IOMUX set failed!\n", hgpio->gpio_num);
        return -1;
    }

    // 配置 GPIO 属性
    cm_gpio_cfg_t cfg = {0};
    cfg.direction = hgpio->direction;
    cfg.pull = hgpio->pull;

    if(cm_gpio_init(hgpio->gpio_num, &cfg) != 0)
    {
        cm_log_printf(0, "GPIO_%d init failed!\n", hgpio->gpio_num);
        return -1;
    }

    cm_log_printf(0, "GPIO_%d initialized successfully!\n", hgpio->gpio_num);
    return 0;
}

// 写 GPIO
int cm_gpio_write(CM_GPIO_Handle_t *hgpio, cm_gpio_level_e level)
{
    if(hgpio == NULL)
        return -1;

    if(cm_gpio_set_level(hgpio->gpio_num, level) != 0)
    {
        cm_log_printf(0, "GPIO_%d write failed!\n", hgpio->gpio_num);
        return -1;
    }

    cm_log_printf(0, "GPIO_%d set level = %d\n", hgpio->gpio_num, level);
    return 0;
}

// 读 GPIO
int cm_gpio_read(CM_GPIO_Handle_t *hgpio, cm_gpio_level_e *level)
{
    if(hgpio == NULL || level == NULL)
        return -1;

    if(cm_gpio_get_level(hgpio->gpio_num, level) != 0)
    {
        cm_log_printf(0, "GPIO_%d read failed!\n", hgpio->gpio_num);
        return -1;
    }

    cm_log_printf(0, "GPIO_%d read level = %d\n", hgpio->gpio_num, *level);
    return 0;
}

// 翻转 GPIO 电平
int cm_gpio_toggle(CM_GPIO_Handle_t *hgpio)
{
    if(hgpio == NULL)
        return -1;

    cm_gpio_level_e level;
    // 读取当前电平
    if(cm_gpio_get_level(hgpio->gpio_num, &level) != 0)
    {
        cm_log_printf(0, "GPIO_%d read failed!\n", hgpio->gpio_num);
        return -1;
    }

    // 翻转电平
    level = (level == CM_GPIO_LEVEL_HIGH) ? CM_GPIO_LEVEL_LOW : CM_GPIO_LEVEL_HIGH;

    // 设置新的电平
    if(cm_gpio_set_level(hgpio->gpio_num, level) != 0)
    {
        cm_log_printf(0, "GPIO_%d toggle failed!\n", hgpio->gpio_num);
        return -1;
    }

    cm_log_printf(0, "GPIO_%d toggled, new level = %d\n", hgpio->gpio_num, level);
    return 0;
}
